package com.jf.exam.controller.manage;

import com.jf.exam.pojo.data.TeacherDO;
import com.jf.exam.pojo.vo.TeacherClassVO;
import com.jf.exam.pojo.vo.TeacherVO;
import com.jf.exam.service.TeacherService;
import com.jf.exam.utils.DataUtils;
import com.jf.exam.utils.PageBean;
import com.jf.exam.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

/**
 * 教师管理
 */
@Controller
@RequestMapping("/admin/teacher")
public class ManageTeacherController {

    @Autowired
    TeacherService teacherService;


    @Value("#{properties['teacher.pageSize']}")
    private int pageSize;

    @Value("#{properties['teacher.navigatePages']}")
    private int navigatePages;


    @RequestMapping("/list")
    public String list(TeacherVO query, Model model) throws Exception {
        model.addAttribute("function", 6);
        query.setPageSize(pageSize);
        query.setSize(navigatePages);
        PageBean<TeacherDO> pageBean = teacherService.listTeacher(query);
        model.addAttribute("pageBean", pageBean);
        model.addAttribute("query", query);
        return "admin/teacher_list";
    }

    @RequestMapping("/add")
    @ResponseBody
    public Result add(TeacherVO teacherVO) throws Exception {
        return teacherService.addTeacher(teacherVO);
    }

    /**
     * 通过id删除教师信息
     *
     * @param tid 学生id
     * @return 删除结果
     */
    @RequestMapping("/delete/{tid}")
    @ResponseBody
    public Result delete(@PathVariable String tid) throws Exception {
        TeacherVO teacherVO = new TeacherVO();
        teacherVO.setId(tid);
        return teacherService.deleteTeacher(teacherVO);
    }

    /**
     * 教师编辑
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(TeacherVO teacher) throws Exception {
        return teacherService.updateTeacher(teacher);
    }


    /**
     * 更改教师所教的班级
     *
     * @param ids 所教的班级数组
     * @param tid 教师id
     */
    @RequestMapping("/addClass")
    @ResponseBody
    public Result addClass(String ids, String tid) {
        ArrayList<TeacherClassVO> tcs = new ArrayList<>();
        if (!DataUtils.isEmpty(ids)) {
            for (String cid : ids.split(",")) {//1,2,3
                //插入新的数据
                TeacherClassVO tc = new TeacherClassVO();
                tc.setFkTeacher(tid);
                tc.setFkClass(Integer.parseInt(cid));
                tcs.add(tc);
            }
        }
        return teacherService.addClass(tcs, tid);
    }
}
